<template>
  <div class='container'>
    <div v-if="showButton" style="margin-bottom: 12px;">
      <!--<el-button style="margin-right: 10px;" @click="handleStart" type="primary">启用</el-button>-->
      <!--<el-button style="margin-right: 10px;" @click="handleStop" type="primary">停用</el-button>-->
      <a :href="downloadInfo.url" :download="downloadInfo.name">
        <el-button type="warning" icon="el-icon-download">下载Excel模板</el-button>
      </a>
      <el-button :loading="true" v-if="!!uploadFileInfo.loading" type="warning">上传中</el-button>
      <el-upload
        ref="uploadButton"
        :action="uploadAction"
        :headers="{Authorization: 'Bearer ' + $store.getters.token}"
        style="display: inline;"
        :on-success="startParse"
        :before-upload="beforeUpload"
      >
        <el-button v-if="!uploadFileInfo.loading" type="success" icon="el-icon-upload">上传Excel</el-button>
      </el-upload>
    </div>
    <el-table stripe
       :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit
      highlight-current-row @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <!--<el-table-column align="center" type="index" label="序号" width="55">-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="状态">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{formatStatus(scope.row.dataStatus)}}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import { dengtaWordList, dengtaWordUpdate } from '../../api/word'
  import { baseUrl, doRequestPost } from '@/utils/request'

  export default {
    name: 'List',
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.searchWord({
        id: '',
        name: this.tableName
      })
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val.map(e => e.id)
      },
      handleStart() {
        if (this.multipleSelection.length === 0) return
        dengtaWordUpdate({
          batchIds: this.multipleSelection,
          dataStatus: 0
        }).then(() => {
          this.getList()
          this.getWords()
          this.$notify({
            title: '成功',
            message: '启用成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      handleStop() {
        if (this.multipleSelection.length === 0) return
        dengtaWordUpdate({
          batchIds: this.multipleSelection,
          dataStatus: 1
        }).then(() => {
          this.getList()
          this.getWords()
          this.$notify({
            title: '成功',
            message: '停用成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      formatStatus(data) {
        switch (data) {
          case 0:
            return '启用'
          case 1:
            return '停用'
        }
      },
      getWords() {
        this.listLoading = false
        const params = {
          type: this.wordType,
          pageNum: this.listQuery.page,
          pageSize: this.listQuery.pageSize,
          parentId: this.listQuery.search
        }
        dengtaWordList(params).then(response => {
          this.tableData = response.Data
          this.total = response.PageInfo.Total * 1
          this.listLoading = false
        })
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getWords()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getWords()
      },
      searchWord(data) {
        // this.showButton = true
        this.listQuery.search = data.id
        this.tableName = data.name
        this.getWords()
      },
      resetTemp() {
        this.temp = {
          id: '',
          name: '',
          dataStatus: 0
        }
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            dengtaWordUpdate(tempData).then(() => {
              this.getList()
              this.getWords()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      getList() {
        const params = {
          pageNum: 1,
          pageSize: 9999,
          type: this.wordType
        }
        dengtaWordList(params).then(response => {
          const temp = {}
          const result = []
          const data = response.Data
          const length = data.length
          for (let i = 0; i < length; i++) {
            temp[data[i].id] = data[i]
          }
          for (let i = 0; i < length; i++) {
            if (temp[data[i].id].parentCode && temp[data[i].parentCode]) {
              if (!temp[data[i].parentCode].children) {
                temp[data[i].parentCode].children = []
              }
              temp[data[i].parentCode].children.push(temp[data[i].id])
            } else {
              result.push(temp[data[i].id])
            }
          }
          this.data[0].children = result
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      renderContent(h, { node, data, store }) {
        return (
          <span class={(node.isLeaf && node.level > 1) ? 'custom-tree-node' : 'custom-tree-node custom-tree-notLeaf'}>
            <span>{node.label}</span>
            <span>
              {node.level === 1 ? <el-button
                size='mini' type='text' on-click={(e) => this.searchWord(node, data, e)}
              >查看分类</el-button> : ''}
              {node.isLeaf && node.level > 1 ? <el-button
                size='mini' type='text' on-click={(e) => this.searchWord(node, data, e)}
              >查看词汇</el-button> : ''}
            </span>
          </span>)
      },
      startParse(response, file, fileList) {
        this.uploadFileInfo.status = '解析中...'
        let fileInfo = response.Data[0]
        const params = {
          operateType: 1,
          parentId: this.listQuery.search,
          vocaType: 2,
          sourceType: 1,
          fileName: fileInfo.fileName
        }
        doRequestPost(baseUrl + 'file/parse', params).then((response) => {
          this.getWords()
          this.$alert('本次导入影响数据' + response.Data[0].successNum + '条', '提示', {
            confirmButtonText: '确定',
            type: 'success'
          })
          let clearFile = () => {
            fileList.splice(fileList.indexOf(file), 1)
          }
          setTimeout(clearFile, 5000)
          this.uploadFileInfo.loading = false
        }).catch(() => {
          this.uploadFileInfo.loading = false
          this.$refs.uploadButton.clearFiles()
        })
      },
      beforeUpload(file) {
        const isJPG = (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (file.type === 'application/vnd.ms-excel')
        const isLt2M = file.size / 1024 / 1024 < 1
        this.uploadFileInfo.loading = true
        this.uploadFileInfo.status = '上传中...'
        if (!isJPG) {
          this.$message.error('请上传Excel文件！')
          this.uploadFileInfo.loading = false

        }
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 1MB!')
          this.uploadFileInfo.loading = false
        }
        return isJPG && isLt2M
      }
    },
    data() {
      return {
        uploadAction: baseUrl + 'file/upload',
        uploadFileInfo: {
          loading: false,
          status: ''
        },
        downloadInfo: {
          url: baseUrl + 'template/灯塔词汇上传模板.xlsx',
          name: '灯塔词汇上传模板'
        },
        list: null,
        total: null,
        listLoading: false,
        showButton: true,
        tableName: '灯塔敏感词',
        wordType: 2,
        multipleSelection: [],
        listQuery: {
          page: 1,
          pageSize: 20,
          search: undefined
        },
        filterText: '',
        props: {
          label: 'name',
          id: 'id'
        },
        data: [{
          name: '词汇管理',
          id: '',
          children: []
        }],
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogStatus: '',
        dialogFormVisible: false,
        tableData: [],
        temp: {
          id: '',
          name: '',
          dataStatus: 0
        },
        rules: {
          id: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          name: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
        }
      }
    }
  }
</script>

<style type="scss" scoped>
  .col {
    margin: auto;
  }

  .card-body {
    margin-top: 1rem;
  }

  .form {
    max-width: 500px !important;
    margin: auto !important;
  }
</style>

<style>
  .el-tag {
    margin-right: 3px;
    background-color: rgba(64, 158, 255, .1);
    color: #409EFF;
    border-radius: 4px;
    padding: 0 3px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, .2);
  }
</style>


